import React, { useState, useEffect, useRef } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';

interface RichTextEditorProps {
  value: string;
  onChange: (html: string) => void;
  height?: number;
  placeholder?: string;
}

const RichTextEditor: React.FC<RichTextEditorProps> = ({
  value,
  onChange,
  height = 400,
  placeholder = '请输入内容...'
}) => {
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const [html, setHtml] = useState(value);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    toolbarKeys: [
      'headerSelect',
      'bold',
      'italic',
      'underline',
      'through',
      '|',
      'color',
      'bgColor',
      '|',
      'fontSize',
      'fontFamily',
      'lineHeight',
      '|',
      'bulletedList',
      'numberedList',
      'todo',
      '|',
      'justifyLeft',
      'justifyRight',
      'justifyCenter',
      'justifyJustify',
      '|',
      'insertLink',
      'uploadImage',
      'insertTable',
      '|',
      'undo',
      'redo',
      '|',
      'fullScreen'
    ]
  };

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder,
    MENU_CONF: {
      uploadImage: {
        // 暂时禁用图片上传，使用base64方式
        server: '',
        fieldName: 'file',
        maxFileSize: 5 * 1024 * 1024, // 5MB
        maxNumberOfFiles: 10,
        allowedFileTypes: ['image/*'],
        onBeforeUpload(file: File) {
          console.log('onBeforeUpload', file);
          return file;
        },
        onProgress(progress: number) {
          console.log('onProgress', progress);
        },
        onSuccess(file: File, res: any) {
          console.log('onSuccess', file, res);
        },
        onFailed(file: File, res: any) {
          console.log('onFailed', file, res);
        },
        onError(file: File, err: any, res: any) {
          console.log('onError', file, err, res);
        },
        customInsert(res: any, insertFn: any) {
          // res 即服务端的返回结果
          console.log('customInsert', res);
          
          // 从 res 中获取图片 url 并插入
          const url = res.data?.url || res.url;
          if (url) {
            insertFn(url, res.data?.alt || '', res.data?.href || '');
          }
        },
        // 使用base64方式处理图片
        customUpload(file: File, insertFn: any) {
          const reader = new FileReader();
          reader.onload = (e) => {
            const result = e.target?.result as string;
            if (result) {
              insertFn(result, file.name, '');
            }
          };
          reader.readAsDataURL(file);
          return false; // 阻止默认上传
        }
      }
    }
  };

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  // 同步 value 到 html
  useEffect(() => {
    setHtml(value);
  }, [value]);

  // 同步 html 到 onChange
  useEffect(() => {
    onChange(html);
  }, [html, onChange]);

  return (
    <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: '1px solid #ccc' }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={html}
        onCreated={setEditor}
        onChange={editor => {
          setHtml(editor.getHtml());
        }}
        mode="default"
        style={{ height }}
      />
    </div>
  );
};

export default RichTextEditor; 